/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.business;

import TimeRecording.tables.Employee;
import TimeRecording.tables.WorkingSummary;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author david
 */
public class EmployeeUtilities {

    /**
     * Reassesses any details of the employee that might change on a daily
     * basis.  At the moment, this amounts to little more than re-assessing the
     * "hours per week" and "average hours per day" figure for the employee.
     * currently visits all records but could be tweaked to only visit those
     * that require re-assessment.  The transaction is managed outside of this
     * method.
     *
     * @param  entityManager the entityManager via which database changes are made
     */
    public void reassessEmployees(EntityManager entityManager) {

        List<Employee> employees = Employee.getEmployees(entityManager);

        for (Employee employee : employees) {

            WorkingSummary patternMaster =
                    employee.getWorkingPatternsMaster();

            // Persist any changes
            if (assessPatternMaster(patternMaster)) {
                entityManager.merge(patternMaster);
            }
        }
    }

    /**
     * This method simply reassesses the hours worked per week and hours worked
     * per day totals.  These figures are based on the working patterns in place
     * for the current week (as this seems the most sensible approach).  These
     * figures are only used for presentation purposes; under the covers
     * everything is calculated in hours.
     *
     * @param patternMaster the master pattern record
     * @return a boolean indicate a change needs to be flashed back to the DB
     */
    public boolean assessPatternMaster(WorkingSummary patternMaster) {

        ScheduledTime scheduledHours = new ScheduledTime();

        double daysWorked = 0;
        double hoursWorked = 0;
        double[] dailyHours = scheduledHours.getSpendForWeek(
                null, patternMaster.getEmployees(), null);

        for (double dailyHour : dailyHours) {
            if (dailyHour != 0) {
                hoursWorked += dailyHour;
                daysWorked++;
            }
        }

        double oldDailyHours = patternMaster.getHoursWorkedPerDay();
        double oldWeeklyHours = patternMaster.getHoursWorkedPerWeek();

        double newWeeklyHours = hoursWorked;
        double newDailyHours = (daysWorked > 0) ? (hoursWorked / daysWorked) : 0;

        boolean changesMade = false;

        if (oldDailyHours != newDailyHours) {
            patternMaster.setHoursWorkedPerDay(newDailyHours);
            changesMade = true;
        }

        if (oldWeeklyHours != newWeeklyHours) {
            patternMaster.setHoursWorkedPerWeek(newWeeklyHours);
            changesMade = true;
        }

        return changesMade;
    }
}
